/* lcn/cmd.c 
 * 
 * This file is part of lcn. 
 * 
 * lcn is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * lcn is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with lcn. If not, see <https://www.gnu.org/licenses/>
 */ 




#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <string.h>
#include <ctype.h>
#include <string.h>

#include <lcn/lcn.h>


/* argv later ... */
int do_cmd_list(char *buf);
int do_cmd_read(char *buf);
int do_cmd_help(char *buf);
int do_cmd_quit(char *buf);

struct cmdtab {
	char 	*name;
	char 	*help_msg;
	int 	(* do_cmd) (char *buf);
} commands[] = {
	{ "list", "List articles (aka ls). ", do_cmd_list }, 
	{ "ls", "List articles (aka list)", do_cmd_list }, 
	{ "read", "Read an article. ", do_cmd_read }, 
	{ "help", "Show help information. ", do_cmd_help}, 
	{ "quit", "Quit lcn (aka exit). ", do_cmd_quit }, 
	{ "exit", "Quit lcn (aka quit). ", do_cmd_quit }, 

	{ NULL, NULL, NULL }
};

int do_command(char *buf) {
	struct cmdtab 	*cmd;
	char 		*p;
	int 		len = 0;

	for (p = buf; *p && !isspace(*p); p++) 
		len++;

	for (cmd = commands; cmd->name; cmd++) 
		if (!strncmp(cmd->name, buf, len)) 
			return cmd->do_cmd(buf);

	fprintf(stderr, "unknown command. \n");
	return 1;
}

int do_cmd_list(char *buf) {
	(void) buf;

	return lcn_list_articles();
}

int do_cmd_read(char *buf) {
	char name[PATH_MAX];

	(void) buf;

	printf("article: ");
	fflush(stdout);
	
	scanf("%s", name);
	return lcn_read_article(name);
}

int do_cmd_help(char *buf) {
	struct cmdtab *cmd;

	(void) buf;

	for (cmd = commands; cmd->name; cmd++) 
		printf("%s: \t\t%s\n", cmd->name, cmd->help_msg);

	return 0;
}


int do_cmd_quit(char *buf) {
	(void) buf;

	printf("bye. \n");
	exit(0);

	return 114514;
}


